#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend

class MailBackend(ModelBackend):
    """
    Backend that allows login with mailadress
    for more info on custom backends see :
    http://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources
    """
    
    supports_object_permissions = True
    
    def authenticate(self, username=None, password=None):
        
        if User.objects.filter(email=username):
                user = User.objects.get(email=username)
        else : 
                return None;
        
        if user.check_password(password) :
                return user;
            


    def get_user(self, id):
        if User.objects.filter(id=id):
            return User.objects.get(id=id)
        else :
            return None
        
    def has_perm(self, user_obj, perm, obj = None):
        
        # If the user has the explicit permission to do stuff: let him do it
        if super(MailBackend, self).has_perm(user_obj, perm):
            return True
        
        # Duck-Typing: if Model has a has_perm: use it
        if (obj != None) and (hasattr(obj, 'has_perm')):
            return obj.has_perm(user_obj, perm)
        
        return False
        

